﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace FileUploadDemoForMVC.Filter
{
    public class ValidateFileAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            int maxContentLength = 1024 * 1024 * 40;
            string[] allowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
            var file = value as HttpPostedFileBase;
            if (file == null)
            {
                ErrorMessage = "文件未收到";
                return false;
            }

            if (!allowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
            {
                ErrorMessage = "请上传你的博客图片类型: " + string.Join(", ", allowedFileExtensions);
                return false;
            }
            if (file.ContentLength > maxContentLength)
            {
                ErrorMessage = "上传图片过大，不能超过40MB。现在的文件容量是：" + file.ContentLength / (1024 * 1024) + "MB";
                return false;
            }
            return true;
        }
    }
}